package com.huobi.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class PushDataExecutor implements InitializingBean {
    private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    private Map<String, Session> sessions = new ConcurrentHashMap<>();
    public static PushDataExecutor self = null;

    public void addSession(Session session){
        sessions.put(session.getId(),session);
    }

    public void  removeSession(Session session){
        sessions.remove(session.getId());
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        self = this;
        Runnable runnable = new Runnable() {
            public void run() {
                Collection<Session> ls = sessions.values();
                ls.forEach(session -> {
                    if (!session.isOpen()) {
                        return;
                    }
                    RemoteEndpoint.Basic basicRemote = session.getBasicRemote();
                    try {
                        basicRemote.sendText("111," + System.currentTimeMillis());
                    } catch (IOException e) {
                        log.error("send ping error.");
                    }
                });
            }
        };
        scheduledExecutorService.scheduleAtFixedRate(runnable,5,1, TimeUnit.SECONDS);
    }
}
